package com.shs.sys.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shs.sys.common.Constants;
import com.shs.sys.common.DataGridView;
import com.shs.sys.common.PinyinUtils;
import com.shs.sys.common.ResultObj;
import com.shs.sys.entity.Dept;
import com.shs.sys.entity.Role;
import com.shs.sys.entity.User;
import com.shs.sys.service.DeptService;
import com.shs.sys.service.RoleService;
import com.shs.sys.service.UserService;
import com.shs.sys.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  用户管理前端控制器
 * </p>
 *
 * @author jxm
 * @since 2020-04-09
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;

    /**
     * 查询用户
     * @param userVo
     * @return
     */
    @RequestMapping("loadAllUser")
    public DataGridView loadAllUser(UserVo userVo){
        IPage<User> page = new Page<>(1,10);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(StringUtils.isNotBlank(userVo.getLoginname()),"loginname",userVo.getLoginname());
        queryWrapper.eq(StringUtils.isNotBlank(userVo.getName()),"name",userVo.getName());
        queryWrapper.eq(StringUtils.isNotBlank(userVo.getAddress()),"address",userVo.getAddress());
        queryWrapper.eq("type",Constants.USER_TYPE_NORMAL);//查询系统用户
        queryWrapper.eq(userVo.getDeptid()!=null,"deptid",userVo.getDeptid());
        userService.page(page,queryWrapper);
        List<User> users = page.getRecords();
        for (User user : users) {
            Integer deptid = user.getDeptid();
            if(deptid!=null){
                Dept dept = deptService.getById(deptid);
                user.setDeptname(dept.getTitle());
            }
            Integer mgr = user.getMgr();
            if(mgr!=null){
                User user1 = userService.getById(mgr);
                user.setLeadername(user1.getName());
            }
        }
        return new DataGridView(page.getTotal(),users);

    }

    /**
     * 获取部门排序码
     */
    @RequestMapping("loadUserMaxOrderNum")
    public Map<String,Object> loadDeptMaxOrderNum(){
        Map<String,Object> result = new HashMap<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        List<User> list = userService.list(queryWrapper);
        if(null!=list && list.size()>0){
            result.put("value",list.get(0).getOrdernum()+1);
        }else{
            result.put("value",1);
        }
        return result;
    }

    /**
     *根据部门ID查询用户
     * @return
     */
    @RequestMapping("loadUserByDeptId")
    public DataGridView loadUserByDeptId(Integer deptid){
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq(deptid!=null,"deptid",deptid);
        wrapper.eq("available",Constants.AVAILABLE_TRUE);
        wrapper.eq("type",Constants.USER_TYPE_NORMAL);
        List<User> list = userService.list(wrapper);
        return new DataGridView(list);
    }

    /**
     *把用户名转成拼音
     * @param username
     * @return
     */
    @RequestMapping("changeChineseToPinyin")
    public Map<String,Object> changeChineseToPinyin(String username){
        Map<String,Object> result = new HashMap<>();
        if(null!=username){
            String pingYin = PinyinUtils.getPingYin1(username);
            result.put("value",pingYin);
        }
        return result;
    }

    /**
     * 添加用户
     */
    @RequestMapping("addUser")
    public ResultObj addUser(UserVo userVo){
        try {
            userVo.setType(Constants.USER_TYPE_NORMAL);
            userVo.setHiredate(new Date());
            //UUID全称通用唯一识别码 生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
            String salt = IdUtil.simpleUUID().toUpperCase();
            userVo.setSalt(salt);
            userVo.setPwd(new Md5Hash(Constants.USER_DEFAULT_PWD,salt,2).toString());
            userService.save(userVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 修改用户
     */
    @RequestMapping("updateUser")
    public ResultObj updateUser(UserVo userVo){
        try {
            userService.updateById(userVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 根据用户id查找用户
     */
    @RequestMapping("loadUserById")
    public DataGridView loadUserById(Integer id){
        return new DataGridView(userService.getById(id));
    }

    /**
     * 删除用户
     */
    @RequestMapping("deleteUser")
    public ResultObj deleteUser(Integer id){
        try {
            userService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }
    /**
     * 重置用户密码
     */
    @RequestMapping("resetPwd")
    public ResultObj resetPwd(Integer id){
        try {
            User user = new User();
            user.setId(id);
            String salt = IdUtil.simpleUUID().toUpperCase();
            user.setSalt(salt);
            user.setPwd(new Md5Hash(Constants.USER_DEFAULT_PWD,salt,2).toString());
            userService.updateById(user);
            return ResultObj.RESET_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.RESET_ERROR;
        }
    }

    /**
     *根据用户ID查询角色并选中已拥有的角色
     */
    @RequestMapping("initRoleByUid")
    public DataGridView initRoleByUid(Integer id){
        //1,查询所有可用的角色
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("available",Constants.AVAILABLE_TRUE);
        List<Map<String, Object>> maps = roleService.listMaps(queryWrapper);
        //2,查询当前用户拥有的角色ID集合
        List<Integer> ids = roleService.queryUserRoleIdsByUid(id);
        for (Map<String, Object> map : maps) {
            Boolean LAY_CHECKED=false; //默认为不选中
            Integer roleId = (Integer)map.get("id");
            for (Integer rid : ids) {
                if(roleId == rid){
                    LAY_CHECKED = true;
                    break;
                }
            }
            map.put("LAY_CHECKED",LAY_CHECKED);
        }
        return new DataGridView(maps);
    }

    /**
     *保存用户和角色的关系
     * @param uid
     * @param ids
     * @return
     */
    @RequestMapping("saveUserRole")
    public ResultObj saveUserRole(Integer uid,Integer[] ids){
        try {
            userService.saveUserRole(uid,ids);
            return ResultObj.DISPATCH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }
}
